<template>
  <v-page
    background="#f5f6fa"
    header-background="white"
    padding-top="24rpx"
    :loading="loading"
  >
    <template #header>
      <v-navbar :title="isModify ? '编辑售后单' : '申请售后'" />
    </template>
    <template #default>
      <view class="aftersales-block">
        <view class="block-info-item">
          <view class="label">
            售后类型
          </view>
          <view class="content">
            {{ aftersalesType }}
          </view>
        </view>
        <view class="block-info-item">
          <view class="label">
            申请原因
          </view>
          <view class="content">
            {{ formData.reason }}
          </view>
        </view>
      </view>
      <view class="aftersales-block">
        <view class="block-info-item">
          <view
            class="label"
            :class="{ required: order?.shipping_status !== 'UNSHIPPED' }"
          >
            售后件数
          </view>
          <view class="content">
            <template v-if="order?.shipping_status !== 'UNSHIPPED'">
              <v-input-number
                v-model="formData.quantity"
                :min="1"
                :max="maxCount"
                action
                :precision="0"
                @change="changeQuantityHandle"
              />
            </template>
            <template v-else>
              {{ formData.quantity }}
            </template>
          </view>
        </view>
      </view>
      <view class="aftersales-block">
        <view class="block-info-item">
          <view
            class="label"
            :class="{ required: order?.shipping_status !== 'UNSHIPPED' }"
          >
            申请金额
          </view>
          <view class="input-content">
            <template v-if="order?.shipping_status !== 'UNSHIPPED'">
              <v-input-number
                v-model="formData.amount"
                type="digit"
                placeholder="请输入申请金额"
                :min="0.01"
                :max="refundAmount"
                :custom-style="{ width: '100%', textAlign: 'right' }"
              />
            </template>
            <template v-else>
              <view>
                {{ refundAmount?.toFixed(2) }}
              </view>
            </template>
            <view v-if="refundAmount" class="sub">
              <template v-if="refundShippingFee">
                {{
                  `最多可退 ¥${refundAmount.toFixed(2)}(含平摊运费¥${refundShippingFee.toFixed(2)})`
                }}
              </template>
              <template v-else>
                {{ `最多可退 ¥${refundAmount.toFixed(2)}` }}
              </template>
            </view>
          </view>
        </view>
      </view>
      <view class="aftersales-block">
        <view class="inline-label required">
          申请描述
        </view>
        <v-textarea
          v-model="formData.customer_remark"
          :custom-style="{ height: '200rpx' }"
          :maxlength="500"
          placeholder="请填写申请描述"
        />
        <v-uploader
          v-model="formData.image"
          v-model:loading="uploading"
          :pre-list="formData.image"
          upload-url="/storefront/v1/file/upload/image"
          upload-name="file"
          :extra-data="{ type: 'ORDER_REFUND_IMAGE' }"
          :max-length="6"
        />
      </view>
      <view class="aftersales-block">
        <view class="block-info-item">
          <view class="label">
            联系电话
          </view>
          <view class="content">
            <v-input
              v-model="formData.mobile"
              type="tel"
              placeholder="请输入联系电话"
              :custom-style="{ width: '100%', textAlign: 'right' }"
              :maxlength="11"
            />
          </view>
        </view>
      </view>
    </template>
    <template #footer>
      <view class="submit-button-container">
        <v-button type="primary" @click="submitHandle">
          确定
        </v-button>
      </view>
    </template>
  </v-page>
</template>

<script setup lang="ts">
const isModify = ref(false);
const aftersalesId = ref('');
const orderId = ref('');
const order = ref<OrderVO>();
const getOrderDetails = async () => {
  const response = await $api.getOrderQueryIdDetail(orderId.value);
  switch (response.__error) {
    case undefined:
      order.value = response.data;
      if (order.value.shipping_status === 'UNSHIPPED') {
        unwatchQuantity?.();
        formData.value.amount = product.value?.behind_refund_amount ?? 0;
        formData.value.quantity = product.value?.behind_refund_num ?? 1;
      }
      break;
  }
};

const product = ref<OrderDetailVO | BackRefundDetailVO>();
const loading = ref(true);
onLoad(async (query) => {
  isModify.value = query?.modify === 'true';

  const pageStore = $store.page();
  const parameters = pageStore.parameters as {
    id: string;
    aftersalesId?: string;
    type: 'BARTER' | 'REFUND' | 'SALE_RETURN';
    reason: string;
    product: OrderDetailVO | BackRefundDetailVO;
    customer_remark?: string;
    image?: string[];
    mobile?: string;
    amount?: number;
    quantity?: number;
  };

  orderId.value = parameters.id;
  formData.value.type = parameters.type;
  formData.value.reason = parameters.reason;
  product.value = parameters.product;
  aftersalesId.value = parameters.aftersalesId ?? '';
  formData.value.customer_remark = parameters.customer_remark ?? '';
  formData.value.image = parameters.image ?? [];
  formData.value.mobile = parameters.mobile;
  formData.value.amount = parameters.amount;
  formData.value.quantity =
    parameters.quantity ?? product.value?.behind_refund_num ?? 1;

  const immediate = typeof parameters.amount !== 'number';
  unwatchQuantity = watch(
    () => formData.value.quantity,
    (val) => {
      if (!val) return;
      let total = product.value?.behind_refund_amount;
      const shippingFee = refundShippingFee.value ?? 0;
      const num = product.value?.behind_refund_num;
      if (total && num) {
        total += shippingFee;
        const singlePrice = total / num;
        const price = singlePrice * val;
        formData.value.amount = Math.ceil(price * 100) / 100;
      } else {
        return undefined;
      }
    },
    { immediate }
  );

  loading.value = true;
  await getOrderDetails();
  loading.value = false;
  if (!order.value) uni.navigateBack();
});

const maxCount = computed(() => {
  return product.value?.behind_refund_num || 1;
});
const refundShippingFee = computed(() => {
  // 待发货的才退运费
  if (order.value?.shipping_status !== 'UNSHIPPED') return undefined;
  const shippingFee = product.value?.shipping_fee ?? 0;
  if (shippingFee) {
    return Math.ceil(shippingFee * 100) / 100;
  } else {
    return 0;
  }
});
const refundAmount = computed(() => {
  let total = product.value?.behind_refund_amount;
  const shippingFee = refundShippingFee.value ?? 0;
  const num = product.value?.behind_refund_num;
  if (total && num) {
    total += shippingFee;
    const singlePrice = total / num;
    const price = singlePrice * formData.value.quantity;
    return Math.ceil(price * 100) / 100;
  } else {
    return undefined;
  }
});
const changeQuantityHandle = () => {
  if (refundAmount.value === undefined) return;
  if (formData.value.amount && formData.value.amount > refundAmount.value) {
    formData.value.amount = refundAmount.value;
  }
};

const formData = ref<{
  /** 联系手机 */
  mobile?: string;
  /** 售后类型 */
  type: 'BARTER' | 'REFUND' | 'SALE_RETURN';
  /** 售后原因 */
  reason: string;
  /** 客户备注 */
  customer_remark: string;
  /** 图片 */
  image?: string[];
  /** 申请金额 */
  amount?: number;
  /** 申请数量 */
  quantity: number;
}>({
  type: 'REFUND',
  reason: '多拍/错拍/不想要',
  customer_remark: '',
  image: [],
  quantity: 1
});

let unwatchQuantity: undefined | (() => void);

const aftersalesType = computed(() => {
  switch (formData.value.type) {
    case 'BARTER':
      return '退货换货';
    case 'REFUND':
      return '仅退款';
    case 'SALE_RETURN':
      return '退货退款';
    default:
      return '';
  }
});

const uploading = ref(false);
const validate = async () => {
  if (uploading.value) {
    uni.showToast({ title: '图片上传中，请稍后', icon: 'none' });
    return false;
  }
  if (!formData.value.quantity) {
    uni.showToast({ title: '请输入申请数量', icon: 'none' });
    return false;
  }
  if (!formData.value.amount) {
    uni.showToast({ title: '请输入申请金额', icon: 'none' });
    return false;
  }
  if (!formData.value.customer_remark) {
    uni.showToast({ title: '请输入申请描述', icon: 'none' });
    return false;
  }
  if (!formData.value.image?.length) {
    uni.showToast({ title: '请上传凭证图片', icon: 'none' });
    return false;
  }
  const mobile = formData.value.mobile;
  if (mobile && !/^1([35689]\d|7[3-8]|4[5-7])\d{8}$/.test(mobile)) {
    uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
    return false;
  }
  return true;
};

const submitHandle = () => {
  if (isModify.value) {
    modifyAftersales();
  } else {
    applyAftersales();
  }
};

const applyAftersales = async () => {
  const isValid = await validate();
  if (!isValid) return;
  uni.showLoading({ mask: true });
  const response = await $api.postBackRefundApply({
    order_id: orderId.value,
    mobile:
      formData.value.mobile || (order.value?.recipient_info?.mobile as string),
    shipping_fee: refundShippingFee.value as number,
    type: formData.value.type as 'BARTER' | 'REFUND' | 'SALE_RETURN',
    reason: formData.value.reason as string,
    customer_remark: formData.value.customer_remark as string,
    image: formData.value.image as string[],
    refund_detail_list: [
      {
        id: product.value?.id as string,
        create_time: '',
        update_time: '',
        order_detail_id: product.value?.id as string,
        quantity: formData.value.quantity,
        apply_amount: formData.value.amount as number
      }
    ]
  });
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '提交成功', icon: 'none' });
      uni.redirectTo({
        url: `/pages/aftersales/aftersales-details?id=${response.data.id}`
      });
      break;
  }
};

const modifyAftersales = async () => {
  const isValid = await validate();
  if (!isValid) return;
  const refundProduct = product.value as BackRefundDetailVO;
  uni.showLoading({ mask: true });
  const response = await $api.putBackRefundModifyId(aftersalesId.value, {
    order_id: orderId.value,
    mobile: formData.value.mobile as string,
    shipping_fee: refundShippingFee.value as number,
    type: formData.value.type as 'BARTER' | 'REFUND' | 'SALE_RETURN',
    reason: formData.value.reason as string,
    customer_remark: formData.value.customer_remark as string,
    image: formData.value.image as string[],
    refund_detail_list: [
      {
        id: refundProduct.order_detail_id as string,
        create_time: '',
        update_time: '',
        order_detail_id: refundProduct.order_detail_id as string,
        quantity: formData.value.quantity,
        apply_amount: formData.value.amount as number
      }
    ]
  });
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '修改成功', icon: 'none' });
      uni.navigateBack();
      break;
  }
};
</script>

<style lang="scss" scoped>
.aftersales-block {
  margin: 0 24rpx 24rpx;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 12rpx;
  .inline-label {
    line-height: 40rpx;
    font-weight: bold;
    &.required::before {
      content: '*';
      color: red;
      margin-right: 4rpx;
    }
  }
  .block-info-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24rpx;
    min-height: 60rpx;
    .label {
      flex-shrink: 0;
      &.required::before {
        content: '*';
        color: red;
        margin-right: 4rpx;
      }
    }
    .sub-label {
      color: #999999;
      font-weight: 300;
      flex: 1;
      min-width: 0;
    }
    .content {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12rpx;
      &.placeholder {
        color: #999999;
        font-weight: 300;
      }
    }
    .input-content {
      flex: 1;
      min-width: 0;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      .sub {
        color: #999999;
        margin-top: 8rpx;
      }
    }
  }
}

.submit-button-container {
  margin: 0 24rpx 24rpx;
  padding: 10rpx 0;
}
</style>
